from django_filters.rest_framework import DjangoFilterBackend

from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from rest_framework.filters import OrderingFilter
from rest_framework import status
from rest_framework.response import Response

from XApiTestServer.models import MockInfo
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import ProjectSerializer, ProjectSumSerializer

from XApiTestServer.utils.common import *
from XApiTestServer.utils.test_report import *
from XApiTestServer.utils.response import *
import logging


logger = logging.getLogger('XApiTestServer')

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = ProjectInfo.objects.all()
    serializer_class = ProjectSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('responsible_name', 'project_name')
    filterset_fields = ('project_name',)
    ordering_fields = ('update_time',)

    def nameValidator(self, projectname, project_id = None):
        if project_id:
            actualname = ProjectInfo.objects.filter(id=project_id).values('project_name')
            if actualname[0]['project_name'] == projectname:
                return False
            else:
                projectlist = ProjectInfo.objects.all().values('project_name')
                for a in projectlist:
                    if a['project_name'] == projectname:
                        return True
                    else:
                        continue
                return False
        else:
            projectlist = ProjectInfo.objects.all().values('project_name')
            for a in projectlist:
                if a['project_name'] == projectname:
                    return True
                else:
                    continue
            return False


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data
        return Response(response_body)

    def create(self, request, *args, **kwargs):
        if request.data['project_name'] == '' or request.data['responsible_name'] == '' or request.data[
            'test_user'] == '' or request.data['dev_user'] == '' or request.data['publish_app'] == '':
            return Response(VERIFY_FIELDS_HINT, status=status.HTTP_201_CREATED)

        if self.nameValidator(request.data['project_name']):
            return Response(PROJECT_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            response_body = {'msg': '{msg}'.format(msg=serializer.errors)}
            return Response(response_body, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):

        if request.data['project_name'] == '' or request.data['responsible_name'] == '' or request.data[
            'test_user'] == '' or request.data['dev_user'] == '' or request.data['publish_app'] == '':
            return Response(VERIFY_FIELDS_HINT, status=status.HTTP_201_CREATED)

        if self.nameValidator(request.data['project_name'],request.data['id']):
            return Response(PROJECT_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        response_body = SUCCESS_UPDATE
        response_body['data'] = serializer.data
        return Response(response_body)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)


class ProjectSumViewSet(viewsets.ModelViewSet):
    queryset = ProjectInfo.objects.all()
    serializer_class = ProjectSumSerializer
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    filterset_fields = ('project_name',)
    ordering_fields = ('update_time',)

    def list(self, request, *args, **kwargs):
        queryset = ProjectInfo.objects.all()

        serializer = self.get_serializer(queryset, many=True)

        response_body = SUCCESS_LIST
        response_body['results'] = serializer.data

        return Response(response_body)
